package com.cmcc.speed

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.location.Location
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.*
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.activity.addCallback
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.work.WorkInfo.State.*
import androidx.work.WorkManager
import com.cmcc.speed.databinding.ActivityMainBinding
import com.cmcc.speed.http.KCHttpV2
import com.cmcc.speed.utils.*
import com.cmcc.speed.utils.CommonUtils.md5
import com.cmcc.speed.utils.CommonUtils.saveBitmapGallery
import com.cmcc.speed.utils.Constants.DATE_FORMAT
import com.cmcc.speed.utils.Constants.PHOTO_EXTENSION
import com.cmcc.speed.utils.Constants.REQUIRED_PERMISSIONS
import com.cmcc.speed.utils.FileUtils.createFile
import com.cmcc.speed.utils.FileUtils.getOutputDirectory
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.launch
import okhttp3.*
import org.json.JSONObject
import java.io.*
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.concurrent.schedule


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    lateinit var activityWebView: WebView
    private var mHandler: Handler? = null
    private var isRootPage: Boolean? = false
    private var lstApi: List<String>? = null
    private var handler: Handler? = null
    private val UPDATE_CONTENT = 1111
    private val TAG = "MainActivity"

    private val APP_ID = "wx88888888"
    // IWXAPI 是第三方 app 和微信通信的 openApi 接口
    private var api: IWXAPI? = null

    var userInfo = ""
    var mDonwlodList = JSONObject()
    var mDonwlodTimeList= JSONObject()
    var isFinish = false
    // 拍照
    private var isShowCameraPage: Boolean? = false
    private var imageCamera: ImageCapture? = null
    private var cameraExecutor: ExecutorService? = null
    var videoCapture: VideoCapture? = null//录像用例
    var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//当前相机
    var preview: Preview? = null//预览对象
    var cameraProvider: ProcessCameraProvider? = null//相机信息
    var camera: Camera? = null//相机对象
    var isRecordVideo: Boolean = false
    private lateinit var outputDirectory: File
    private var lensFacing: Int = CameraSelector.LENS_FACING_BACK

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val intent = Intent()
        userInfo = intent.getStringExtra("user").toString()


        // 初始化message监听
        initData()
        // 初始化微信sdk
        intWxShare()

        activityWebView = binding.toolWebview
        setWebWs()
//        activityWebView.loadUrl("file:///android_asset/www/index.html")
//        activityWebView.loadUrl("http://cmcc-speed.gitee.io/cmcc-app")
//        activityWebView.loadUrl("http://192.168.3.18:5173")
        activityWebView.loadUrl("http://st3.zdyspace.com/app")
        binding.addButton.setOnClickListener {
            binding.adView.visibility = View.INVISIBLE
        }
        var TotalTime : Long = 3000 //总时长 2小时
        var countDownTimer=object : CountDownTimer(TotalTime,1000){//1000ms运行一次onTick里面的方法
            override fun onFinish() {
                binding.adView.visibility = View.INVISIBLE
            }

            override fun onTick(millisUntilFinished: Long) {
                binding.addButton.text = "跳过"+millisUntilFinished/1000+"s"
            }
        }.start()


        initPermission()
//        getNetName(this)

        onBackPressedDispatcher.addCallback(this, true) {
            Log.e("onBackPressedDispatcher", "touching")
            if (isRootPage == true) {
                binding.cameraView.visibility = View.INVISIBLE
                isRootPage = false
            } else {
                if (isRootPage == true) {
                    isRootPage = false
                    finish()
                } else {
                    callJsFun("goBack", null)
                }
            }
        }

        // 拍照
        outputDirectory = getOutputDirectory(this)

        val ipaddress = CommonUtils.getIPAddress(true)
        val json = JSONObject();
        json.put("ip", ipaddress)
        callJsFun("ipaddress", json)
    }

    fun intWxShare() {
        // 通过 WXAPIFactory 工厂，获取 IWXAPI 的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true)
        // 将应用的 appId 注册到微信
        api!!.registerApp(APP_ID)
        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该 app 注册到微信
                api!!.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    @SuppressLint("JavascriptInterface")
    private fun setWebWs() {
        activityWebView.background.alpha = 0; // 设置填充透明度 范围：0-255
        activityWebView.webViewClient = WebViewClient()
        val ws: WebSettings? = activityWebView?.settings
        //注释先不要删掉
        //ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        ws?.javaScriptCanOpenWindowsAutomatically = false;//自动打开窗口
//        ws?.setSupportZoom(true);// 设置支持缩放
        ws?.builtInZoomControls = true;// 设置支持缩放
        ws?.displayZoomControls = false;//显示缩放按
        ws?.allowFileAccess = true;// -> 是否允许访问文件
        ws?.domStorageEnabled = true; //-> 是否节点缓存
        ws?.databaseEnabled = true;// -> 是否数据缓存
        ws?.setAppCacheEnabled(true);// -> 是否应用缓存
        ws?.loadWithOverviewMode = true
        ws?.builtInZoomControls = true
        //? ws.setAllowFileAccessFromFileURLs(false);
        //? ws.setAllowFileAccessFromFileURLs(false);
        ws?.useWideViewPort = true //图片被缩放后显示不全的问题
        ws?.javaScriptEnabled = true
        ws?.savePassword = false
        ws?.blockNetworkImage = false
        ws?.loadsImagesAutomatically = true
//        var oldUA = ws?.userAgentString
        //UA都是跟h5约定好提供什么参数
//        val addAgent =
//            " AppName/(${ChicvUserAgentDataManager.getAppName()}) LanguageId/($language_id) Language/($language_code) Currency/($currency_code) CurrencyId/($country_id) WappBrowser/1.2.6 ChannelId/(1) PlatformId/(1) LastLoginTime/ Version/(${
//                getVersionName(MyApplication.getInstance())
//            }) SystemVersion/(${ChicvUserAgentDataManager.getOsVersion()})"
//        ws?.userAgentString = oldUA + addAgent

        val timecurrentTimeMillis = System.currentTimeMillis()
//        val sign = MD5Util.getMD5("SECRET")
//        val language_id = language_id
//        val language_code = language_code
//        val currency_code = currency_code
//        val country_id = currencyCountry_id.toString()

        activityWebView?.addJavascriptInterface(this, "local_android");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0以上默认不允许http和https混合模式, 需手动开启
            ws?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
//        activityWebView.webChromeClient = BaseWebChromeClient()
//        activityWebView.webViewClient = BaseWebViewClient(activityWebViewProgressbar)
        //设置cookie
//        syncCookie()
//        val token = if (GlobalFunc.hasLogin()) GlobalFunc.getAccountToken() else ""
//        var cookies = if (token.isNullOrEmpty()) "currency=$currency_code;language=$language_id;language-code=$language_code" else "access_token=$token;currency=$currency_code;language=$language_id;language-code=$language_code"
        //设置header,给后端使用
//        val headerMap = mapOf(
//            "x-origin-client" to "Android",
//        )
    }

    private fun callJsFun(functionName: String, params: JSONObject?) {
        Log.e("onReceiveValue:$functionName", params.toString())
        activityWebView.evaluateJavascript("javascript:$functionName($params)") { p0 ->
            Log.e(
                "onReceiveValue",
                p0
            )
        }
    }

    @JavascriptInterface
    fun getUserInfo() {
        val json = JSONObject();
//        json.put("user", "{\"phone\": 13228045886, \"id\":12}")
        json.put("user", userInfo)
        activityWebView.post(Runnable {
            callJsFun("setUserInfo", json)
        })
    }

    @JavascriptInterface
    fun goExit() {
        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
        isRootPage = true
        Timer().schedule(3000) {
            isRootPage = false
        }
    }

    @JavascriptInterface
    fun cameraGetRouter(title: String) {
        activityWebView.post(Runnable {
            binding.cameraView.visibility = View.VISIBLE
            isRootPage = true
            binding.textCamera.text = title
            startCamera()
        })
    }

    @JavascriptInterface
    fun getNetInfo(startTest:Boolean) {
        activityWebView.post(Runnable {
            getNetName(this, startTest)
        })
    }

    @JavascriptInterface
    fun goHouseWifi() {
        activityWebView.post(Runnable {
            val intent=Intent();
            intent.setClass(this,HouseActivity::class.java)
            startActivity(intent)
        })
    }

    fun getLocaltionInfo(){
        LocationUtils.getInstance(this)!!.getLocation(object : LocationUtils.LocationCallBack {
            override fun setLocation(location: Location?) {
                if (location != null) {
                    val json = JSONObject();
                    json.put("longitude", location.longitude)
                    json.put("latitude", location.latitude)
                    Timer().schedule(3000){
                        activityWebView.post(Runnable {
                            callJsFun("setLocaltionInfo", json)
                        })
                    }
                }
            }

            override fun setAddress(address: android.location.Address?) {
                if (address != null) {
                    val json = JSONObject();
                    json.put("country", address.countryName)
                    json.put("locality", address.locality)
                    json.put("around", LocationUtils.getInstance(this@MainActivity)!!.getAddressLine(address))
                    Timer().schedule(3000){
                        activityWebView.post(Runnable {
                            callJsFun("setLocaltionInfo", json)
                        })
                    }
                }
            }
        })
    }
    // 处理网络
    fun getNetName(ctx: Context, startTest: Boolean) {
        var netName = ""
        val wifiManager: WifiManager = this.getSystemService(Context.WIFI_SERVICE) as WifiManager
        var wifiInfo = wifiManager.connectionInfo
        val scanResults: List<ScanResult> = wifiManager.scanResults;
        var shortList = "{"
        for (i in scanResults.indices) {
            val item: ScanResult = scanResults[i]
            var splitStr = ""
            if(i != 0) splitStr = ","
            shortList += splitStr+"\""+item.SSID+"\":\""+item.level+"\""
        }
        shortList += "}"
        var wifiName = wifiInfo.ssid
        if (wifiName.contains("\"")) {
            wifiName = wifiName.substring(1, wifiName.length - 1)
        }
        //在所用的activity里使用上面的方法
        when (CommonUtils.checkNetworkTypeStr(ctx)) {
            "移动网络" -> netName = "移动网络"
            "网络错误" -> netName = "网络错误"
            "有线网络" -> netName = "有线网络"
            "无线网络" -> netName = wifiName
        }
        //现在获取网络状态都需要定位权限
        if (netName == "<unknown ssid>") {
            netName = "请开启定位，确认wifi"
        }

        val json = JSONObject();
        json.put("netName", netName)
        json.put("rssi", wifiInfo.rssi)
        json.put("linkSpeed", wifiInfo.linkSpeed)
        json.put("linkedDevices", 4)
        json.put("disturb", 2)
        json.put("frequenc", wifiInfo.frequency)
        json.put("startTest", startTest)
        json.put("ip", CommonUtils.intToIp(wifiInfo.ipAddress))
        json.put("mac", wifiInfo.macAddress)
        json.put("networkId", wifiInfo.networkId)
        json.put("scanResults", shortList)
        // 路由mac
        json.put("bssid", wifiInfo.bssid)
        var wifiStandard = ""
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            json.put("wifiStandard", wifiInfo?.wifiStandard)
        } else {
            if (wifiInfo.linkSpeed <= 11) wifiStandard =  "802.b";
            else if (wifiInfo.linkSpeed <= 54) wifiStandard =  "802.g";
            else if (wifiInfo.linkSpeed <= 300) wifiStandard =  "802.11n";
            else if (wifiInfo.linkSpeed <= 866.5) wifiStandard =  "802.11ac";

            json.put("wifiStandard", 5)
        }
        activityWebView.post(Runnable {
            callJsFun("setNetInfo", json)
        })

    }


    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == Constants.REQUEST_CODE_PERMISSIONS) {
            for (i in permissions.indices) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    getNetName(this, false)
                    getLocaltionInfo()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun initPermission() {
        var btnCameraCapture = binding.btnCameraCapture
        if (allPermissionsGranted()) {
            // ImageCapture
            getNetName(this, false)
            getLocaltionInfo()
        } else {
            ActivityCompat.requestPermissions(
                this, REQUIRED_PERMISSIONS, Constants.REQUEST_CODE_PERMISSIONS
            )
        }
        btnCameraCapture.setOnClickListener {
            takePhoto()
        }
        binding.btnBack.setOnClickListener {
            binding.cameraView.visibility = View.INVISIBLE
        }
        binding.btnHandle.setOnClickListener {
            binding.cameraView.visibility = View.INVISIBLE
            val rootObject = JSONObject()
            rootObject.put("result", "{\"data\":{},\"code\":\"0\"}")
            activityWebView.post(Runnable {
                callJsFun("orcText", rootObject)
            })
        }
//        binding.btnSwitch.setOnClickListener {
//            cameraSelector = if (cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) {
//                CameraSelector.DEFAULT_FRONT_CAMERA
//            } else {
//                CameraSelector.DEFAULT_BACK_CAMERA
//            }
//            if (!isRecordVideo) {
//                startCamera()
//            }
//        }
//        binding.btnOpenCamera.setOnClickListener {
//            val intent = Intent(this, CameraActivity::class.java)
//            startActivity(intent)
//        }
    }

    /**
     * 开始相机预览
     */
    @SuppressLint("RestrictedApi")
    private fun startCamera() {
        var viewFinder = binding.viewFinder
        binding.cameraFile.visibility = View.INVISIBLE
        binding.viewFinder.visibility = View.VISIBLE
        cameraExecutor = Executors.newSingleThreadExecutor()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            cameraProvider = cameraProviderFuture.get()//获取相机信息

            //预览配置
            preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(viewFinder.createSurfaceProvider())
                }

            imageCamera = ImageCapture.Builder()
                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                .build()

            try {
                cameraProvider?.unbindAll()//先解绑所有用例
                camera = cameraProvider?.bindToLifecycle(
                    this,
                    cameraSelector,
                    preview,
                    imageCamera
                )//绑定用例
            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 开始拍照
     */
    private fun takePhoto() {
        val imageCapture = imageCamera ?: return
        val photoFile = createFile(outputDirectory, DATE_FORMAT, PHOTO_EXTENSION)
        val metadata = ImageCapture.Metadata().apply {
            // Mirror image when using the front camera
            isReversedHorizontal = lensFacing == CameraSelector.LENS_FACING_FRONT
        }
        /*      val mFileForMat = SimpleDateFormat(DATE_FORMAT, Locale.US)
              val file = File(FileManager.getAvatarPath(mFileForMat.format(Date()) + ".jpg"))*/
        val outputOptions =
//            ImageCapture.OutputFileOptions.Builder(photoFile).setMetadata(metadata).build();
        imageCapture.takePicture(ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageCapturedCallback() {
                override fun onError(exc: ImageCaptureException) {
                    Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
                    ToastUtils.shortToast(" 拍摄失败 ${exc.message}")
                }
                override fun onCaptureSuccess(image: ImageProxy){
                    ToastUtils.shortToast(" 拍摄成功")
                    val bitmap: Bitmap = CommonUtils.imageProxyToBitmap(image);
                    var matrix = Matrix()
                    matrix.postRotate(90.0F)
                    // 创建新的图片
                    var resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.width, bitmap.height, matrix, true);
                    binding.cameraFile.setImageBitmap(resizedBitmap)
                    binding.viewFinder.visibility = View.INVISIBLE

                    val bos = ByteArrayOutputStream()
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bos)

                    binding.cameraFile.visibility = View.VISIBLE
                    val image2: ByteArray = bos.toByteArray()
                    val base64Encoded = Base64.getEncoder().encodeToString(image2)

                    val rootObject = JSONObject()
                    rootObject.put("image", base64Encoded)
                    getOcrText(base64Encoded)
                    image.close()
                }
//                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
//                    cameraProvider?.unbindAll()
//                    val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
//                    ToastUtils.shortToast(" 拍摄成功")
//                    Log.d(TAG, savedUri.path.toString())
//                    val mimeType = MimeTypeMap.getSingleton()
//                        .getMimeTypeFromExtension(savedUri.toFile().extension)
//                    MediaScannerConnection.scanFile(
//                        this@MainActivity,
//                        arrayOf(savedUri.toFile().absolutePath),
//                        arrayOf(mimeType)
//                    ) { _, uri ->
//                        Log.d(TAG, "Image capture scanned into media store: $uri")
//                    }
//
//                    val bitmap: Bitmap =
//                        BitmapFactory.decodeStream(contentResolver.openInputStream(savedUri))
//
//                    binding.viewFinder.visibility = View.INVISIBLE
//
//                    val bos = ByteArrayOutputStream()
//                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bos)
//                    binding.cameraFile.setImageBitmap(bitmap)
//                    binding.cameraFile.visibility = View.VISIBLE
//                    val image: ByteArray = bos.toByteArray()
//
//                    val base64Encoded = Base64.getEncoder().encodeToString(image)
//
//                    val rootObject = JSONObject()
//                    rootObject.put("image", base64Encoded)
//                    getOcrText(base64Encoded)
//                    activityWebView.post(Runnable {
////                        callJsFun("orcText", rootObject)
//                        binding.cameraView.visibility = View.INVISIBLE
//                    })
//                }
            })
    }


    private fun getOcrText(base64Encoded: String) {
        val APIKey = "a1e1637df3f086d4c83c03473026318b"
        val curTime = (System.currentTimeMillis() / 1000).toInt().toString()
        val param = "eyJsYW5ndWFnZSI6ImVuIiwibG9jYXRpb24iOiJmYWxzZSJ9"

        val header = mutableMapOf<String, String>()

        header["X-Appid"] = "d2b057d1"
        header["X-CurTime"] = curTime
        header["X-Param"] = param
        header["Content-type"] = "multipart/form-data"
        header["X-CheckSum"] = md5(APIKey + curTime + param)
        header["Connection"] = "close"

        val url = "https://webapi.xfyun.cn/v1/service/v1/ocr/general"
        val client = OkHttpClient()
        val body: RequestBody = FormBody.Builder()
            .add("image", base64Encoded)
            .build()

        val requestBuilder = Request.Builder().url(url)


        val requst: Request = Request.Builder()
            .url("https://webapi.xfyun.cn/v1/service/v1/ocr/general")
            .addHeader("X-Appid", "d2b057d1")
            .addHeader("X-CurTime", curTime)
            .addHeader("X-Param", param)
            .addHeader("Content-type", "multipart/form-data")
            .addHeader("X-CheckSum", md5(APIKey + curTime + param))
            .post(body)
            .build()
        client.newCall(requst).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                activityWebView.post(Runnable {
                    binding.cameraView.visibility = View.INVISIBLE
                })
                Log.e("go failure ${e.message}", "")
                ToastUtils.shortToast("调用ocr失败")
            }

            override fun onResponse(call: Call, response: Response) {
                activityWebView.post(Runnable {
                    binding.cameraView.visibility = View.INVISIBLE
                })
                val msg = if (response.isSuccessful) {
                    response.body?.string()
                } else {
                    "failure code:${response.code} message:${response.message}"
                }
//                Log.e(msg, "")

                val rootObject = JSONObject()
                rootObject.put("result", msg)
                activityWebView.post(Runnable {
                    callJsFun("orcText", rootObject)
                })
            }

        })

    }

    @JavascriptInterface
    fun download(nodeUrl:String) {

        isFinish = false
        val startTime = System.currentTimeMillis()
        for(index in 0 until 8){
            val rootObject = JSONObject()
            rootObject.put("responseTime", System.currentTimeMillis())
            mDonwlodTimeList.put("$index",rootObject)
            mDonwlodList.put("$index", JSONObject())

            val r = UUID.randomUUID().toString().replace("-", "")
            var baseUrl = if(nodeUrl.isNotEmpty()) nodeUrl  else "https://node-120-192-192-33.speedtest.cn:51090"
            var url = "$baseUrl/download?size=25000000&r=$r"
//            val startDownload = DownloadWorker.startDownload(
//                this@MainActivity,
//                url,
//                this@MainActivity.cacheDir.path,
//                "test.txt"
//            )
//            onWorkDownProcess(startDownload,i)

            lifecycleScope.launch {
                KCHttpV2.download(
                    url,
                    "${this@MainActivity.cacheDir.path}/${"test.txt"}",
                    onProcess = { currentLength, length, process ->
//                        Log.i("currentLength length", "currentLength =$currentLength length=$length process=$process \n")
                        if(System.currentTimeMillis() - startTime < 7000){
                            if(!isFinish){
                                var responseTime = mDonwlodTimeList.getJSONObject("$index")?.getLong("responseTime")
                                if(mDonwlodTimeList.getJSONObject("$index")?.getLong("responseTime")!! > 1000000){
                                    mDonwlodTimeList.getJSONObject("$index")?.put("responseTime", System.currentTimeMillis()- responseTime!!)
                                }
                                mDonwlodList.getJSONObject("$index")?.put("loaded", currentLength)
                                mDonwlodList.getJSONObject("$index")?.put("progress", process)
//                                Log.e("下载进度：progress =${process*100}% \n","")
                                activityWebView.post(Runnable {
                                    val rootObject = JSONObject()
                                    rootObject.put("donwlodTimeList", mDonwlodTimeList)
                                    rootObject.put("donwlodList", mDonwlodList)
                                    callJsFun("downloadUpdate", rootObject)
                                })
                            }
//                            Log.i("download", "process =${(process * 100).toInt()}% \n")
                        }


                        if(process >=1){
                            isFinish = true
                        }
                    },
                    onSuccess = {
                        Log.i("download", filesDir.path)
                    },
                    onError = {
                        it.printStackTrace()
                    })
            }
        }
    }


    private fun onWorkDownProcess(startDownload: UUID,index: Int) {
        WorkManager.getInstance(applicationContext)
            .getWorkInfoByIdLiveData(startDownload)
            .observe(this@MainActivity) { t -> // 任务执行完毕之后，会在这里获取到返回的结果
                when (t?.state) {
                    RUNNING -> {
                        var progress = t.progress.getInt("progress", 0)

                        if(!isFinish){
//                            var responseTime = mDonwlodTimeList[index]?.getLong("responseTime")
//                            if(mDonwlodTimeList[index]?.getLong("responseTime")!! > 1000000){
//                                mDonwlodTimeList[index]?.put("responseTime", System.currentTimeMillis()- responseTime!!)
//                            }
//                            mDonwlodList[index]?.put("loaded", 1048576*progress)
//                            mDonwlodList[index]?.put("progress", progress/100)
//                            Log.e("下载进度：progress =${progress}% \n","")
//                            activityWebView.post(Runnable {
//                                val rootObject = JSONObject()
//                                rootObject.put("donwlodTimeList", mDonwlodTimeList)
//                                rootObject.put("donwlodList", mDonwlodList)
//                                callJsFun("downloadUpdate", rootObject)
//                            })
                        }

                        if(progress ===100){
                            isFinish = true
                        }
                    }
                    SUCCEEDED -> {
                        Log.e("下载成功\n","")
                    }
                    FAILED -> {
                        Log.e("下载失败\n","")
                    }
                    else -> {}
                }
            }
    }

    @SuppressLint("HandlerLeak")
    private fun initData() {
        handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                val obj = msg.obj.toString()
                when (msg.what) {
                    UPDATE_CONTENT -> activityWebView.post(Runnable {
                        val rootObject = JSONObject()
                        rootObject.put("data", obj)
                        callJsFun("pingRes", rootObject)
                    })
                }
            }
        }
    }

    @JavascriptInterface
    fun pingUrl(api: String) {
        Thread {
            var pingNetEntity = PingNetEntity(api, 3, 5, StringBuffer())
            pingNetEntity = PingNet.ping(pingNetEntity)
            Log.e("testPing", pingNetEntity.ip)
            Log.e("testPing", "time=" + pingNetEntity.pingTime)
            Log.e("testPing", pingNetEntity.isResult.toString() + "")
            val msg = Message()
            msg.obj = "${pingNetEntity.ip}, ${pingNetEntity.pingTime}"
            msg.what = UPDATE_CONTENT
            handler!!.sendMessage(msg)
        }.start()
    }

    fun stringToBitmap(image: String): Bitmap? {
        val imageBytes = Base64.getDecoder().decode(image)
        return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
    }
    fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray? {
        val output = ByteArrayOutputStream()
        bmp.compress(CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bmp.recycle()
        }
        val result = output.toByteArray()
        try {
            output.close()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return result
    }

    @JavascriptInterface
    // 微信分享
    fun wxShare(image: String) {
        val bmp = stringToBitmap(image)

        //初始化 WXImageObject 和 WXMediaMessage 对象
        val imgObj = WXImageObject(bmp)
        val msg = WXMediaMessage()
        msg.mediaObject = imgObj

        //设置缩略图
        val thumbBmp = Bitmap.createScaledBitmap(bmp!!, bmp.width, bmp.height, true)
        msg.thumbData = bmpToByteArray(thumbBmp, true)
        bmp.recycle()

        //构造一个Req
        val req = SendMessageToWX.Req()
        req.transaction = "img"+System.currentTimeMillis()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
//        req.userOpenId = getOpenId()
        //调用 api 接口，发送数据到微信
        api!!.sendReq(req)
    }

    @JavascriptInterface
    fun saveImg(image: String) {
        val bmp = stringToBitmap(image)
        val result = saveBitmapGallery(this@MainActivity, bmp!!)
        ToastUtils.shortToast(" 保存 ${if(result) "成功" else  "失败"}")
    }

}
